package com.le.tester.imooc.oldfairy;

import ch.qos.logback.core.joran.action.NewRuleAction;

import java.util.LinkedList;
import java.util.Random;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * createTime：2021/8/25 11:14
 * description：生产者和消费者
 */
public class ProducerCustomerModel {
    private static final int MAX = 10;
    private LinkedList<Integer> queue = new LinkedList<>();

    //锁的信号源
    ReentrantLock lock = new ReentrantLock();
    Condition full = lock.newCondition();
    Condition empty = lock.newCondition();

    public int readData() throws InterruptedException {
        Thread.sleep((long) (Math.random() * 1000));
        return (int) Math.floor(Math.random());
    }

    //生产
    public void readDb() throws InterruptedException {
        //配套使用synchronized->wait->notify(notifyAll)
        //ReentrantLock->await->singleAll
        lock.lock();
        if (MAX == queue.size()) {
            full.await();
            return;
        }
        if (queue.size() == 1) {
            empty.signalAll();
        }
        int i = readData();
        queue.add(i);
        lock.unlock();
    }

    //消费
    public void calculate() throws InterruptedException {
        lock.lock();
        if (0 == queue.size()) {
            empty.await();
            return;
        }
        if (MAX - 1 == queue.size()) {
            full.signalAll();
        }
        Integer remove = queue.remove();
        System.out.println("queue size is " + queue.size());
        remove *= 100;
        lock.unlock();

    }

    public static void main(String[] args) {
        ProducerCustomerModel producerCustomerModel = new ProducerCustomerModel();
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                while (true) {
                    try {
                        producerCustomerModel.readDb();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e.getMessage());
                    }
                }
            }).start();
        }
        new Thread(() -> {
            while (true) {
                try {
                    //Thread.sleep(1000);
                    producerCustomerModel.calculate();
                } catch (Exception e) {
                    throw new RuntimeException(e.getMessage());
                }
            }
        }).start();
    }
}
